package com.wb.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wb.reggie.common.BaseContext;
import com.wb.reggie.common.CustomException;
import com.wb.reggie.entity.*;
import com.wb.reggie.mapper.OrdersMapper;
import com.wb.reggie.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

@Service
public class OrdersServiceImpl extends ServiceImpl<OrdersMapper, Orders> implements OrdersService {

    @Autowired
    private ShoppingCartService shoppingCartService;

    @Autowired
    private UserService userService;

    @Autowired
    private AddressBookService addressBookService;

    @Autowired
    private OrderDetailService orderDetailService;

    /**
     * 用户下单
     * @param orders
     */
    @Transactional
    public void submit(Orders orders) {
        //获得当前用户id
        Long userId = BaseContext.getCurrentId();

        //查询当前购物车的数据
        LambdaQueryWrapper<ShoppingCart> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ShoppingCart::getUserId,userId);
        List<ShoppingCart> shoppingCarts = shoppingCartService.list(queryWrapper);

        if(shoppingCarts == null || shoppingCarts.size() == 0){//购物车为空则抛出业务异常
            throw new CustomException("购物车为空");
        }

        //查询用户数据
        User user = userService.getById(userId);

        //查询地址 （由于请求中有地址id，所以从orders中获取即可）
        Long addressBookId = orders.getAddressBookId();

        AddressBook addressBook = addressBookService.getById(addressBookId);
        if(addressBook == null){//如果地址信息拿不到，就无法给用户派送
            throw new CustomException("用户地址信息有误，无法下单");
        }

        Long orderId = IdWorker.getId();//这个是啥？

        AtomicInteger amount = new AtomicInteger(0);//总金额

        //遍历购物车数据，从购物车的每项菜品或套餐的数据中，依依添加到订单明细实体中，并且累加金额
        List<OrderDetail> orderDetails =shoppingCarts.stream().map((item) -> {
            OrderDetail orderDetail = new OrderDetail();
            orderDetail.setOrderId(orderId);
            orderDetail.setNumber(item.getNumber());//菜品或者套餐的份数
            orderDetail.setDishFlavor(item.getDishFlavor());//菜品的口味
            orderDetail.setDishId(item.getDishId());//菜品id
            orderDetail.setSetmealId(item.getSetmealId());//套餐id
            orderDetail.setName(item.getName());//菜品或套餐名称
            orderDetail.setImage(item.getImage());//图片名称
            orderDetail.setAmount(item.getAmount());//当前金额（单份的金额）
            //总金额：累加，相当于 +=  （上面new出来时传了0，从0开始累加） 累加（单份金额乘以分数）
            amount.addAndGet(item.getAmount().multiply(new BigDecimal(item.getNumber())).intValue());
            return orderDetail;
        }).collect(Collectors.toList());

        //向订单表插入数据，一条数据
        orders.setId(orderId);//也可以设置id为订单号
        orders.setOrderTime(LocalDateTime.now());//设置下单时间
        orders.setCheckoutTime(LocalDateTime.now());//支付时间 随便填个时间，不开发支付功能
        orders.setStatus(2);//状态：2  待派送
        orders.setAmount(new BigDecimal(amount.get()));//总金额
        orders.setUserId(userId);
        orders.setNumber(String.valueOf(orderId));//订单号
        orders.setUserName(user.getName());//用户
        orders.setConsignee(addressBook.getConsignee());//收货人
        orders.setPhone(addressBook.getPhone());//收货人电话
        //地址，拼接 省 市 区 和地址表的详细信息
        orders.setAddress((addressBook.getProvinceName() == null ? "":addressBook.getProvinceName()) +
                (addressBook.getCityName() == null ? "":addressBook.getCityName()) +
                (addressBook.getDistrictName() == null ? "":addressBook.getDistrictName()) +
                (addressBook.getDetail() == null ? "":addressBook.getDetail()));

        this.save(orders);

        //向订单明细表插入数据，可能是多条数据
        orderDetailService.saveBatch(orderDetails);
        //清空购物车数据
        shoppingCartService.remove(queryWrapper);
    }
}
